﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProgNetComponents.Log;

namespace ProgNetComponents.Data.Query
{
    public static class SelectDataCache
    {
        public static Type DataManagerType
        {
            get;
            set;
        }

        private static SelectDataCollection _AllItems = new SelectDataCollection();

        private static Logger _Logger = null;
        /// <summary>
        /// Gets or sets Logger. If not set Logger.Default will be used
        /// </summary>
        public static Logger Logger
        {
            get
            {
                if (_Logger == null)
                    return Logger.Default;
                return _Logger;
            }
            set { _Logger = value; }
        }

        public static SelectData GetData(string Name)
        {
            SelectData item = _AllItems[Name];
            if (item == null && "".IsAppRunning())
                Logger.Log("SelectDataCache.SelectData() - No SelectData with name " + Name);
            return item;
        }
        
        public static void Register(SelectData item, string connectionString = null)
        {
            try
            {
                _AllItems.Add(item);
                DataManager m = Activator.CreateInstance(DataManagerType) as DataManager;
                if (connectionString.IsNotNull())
                    m.ConnectionString = connectionString;
                item.SingleRecordManager = m;
                DataManager m2 = Activator.CreateInstance(DataManagerType) as DataManager;
                if (connectionString.IsNotNull())
                    m.ConnectionString = connectionString;
                item.MultiRecordManager = m2;
            }
            catch (Exception ex)
            {
                Logger.Log(ex, "SelectDataCache.Register()");
            }
        }
        public static void Register(SelectDataCollection collection)
        {
            foreach (SelectData d in collection)
                Register(d);
        }
        public static void Unregister(string name)
        {
            _AllItems.Remove(name);
        }
    }
}
